package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.ImageViews;
import com.chain.BrotherExchange.viewmodel.ChargeMoneyViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.example.common.zxing.encoding.EncodingHandler;

import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 充币
 */
public class ChargeMoneyActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.address_text) TextView addressText;
    @Bind(R.id.coin_unit_text) TextView coinUnitText;
    @Bind(R.id.balance_text_view) TextView balanceTextView;
    @Bind(R.id.address_image_view) ImageView addressImageView;
    @Bind(R.id.save_rq_image_view) TextView saveRqImageView;
    @Bind(R.id.copy_address_view) TextView copyAddressView;

    private Bitmap mAddressBitmap;
    private ChargeMoneyViewModel mViewModel;

    public static void launch(TextView balanceView, TextView typeView, String id) {
        Activity activity = (Activity) balanceView.getContext();
        Pair balancePair = new Pair<>(balanceView, ViewCompat.getTransitionName(balanceView));
        Pair typePair = new Pair<>(typeView, ViewCompat.getTransitionName(typeView));
        ActivityCompat.startActivity(activity,
                new Intent(activity, ChargeMoneyActivity.class)
                        .putExtra(C.EXTRA_BALANCE, balanceView.getText().toString())
                        .putExtra(C.EXTRA_COIN_TYPE, typeView.getText().toString())
                        .putExtra(C.EXTRA_COIN_ID, id),
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity, balancePair, typePair).toBundle());
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_charge_money;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_charge_money);

        // 余额及货币类型
        balanceTextView.setText(getIntent().getStringExtra(C.EXTRA_BALANCE));
        coinUnitText.setText(getIntent().getStringExtra(C.EXTRA_COIN_TYPE));

        mViewModel = ViewModelProviders.of(this).get(ChargeMoneyViewModel.class);
        initChargeMoney();
    }

    private void initChargeMoney() {
        String id = getIntent().getStringExtra(C.EXTRA_COIN_ID);
        mViewModel.chargeMoney(id).observe(this, resource -> {
                    if (resource.state == Resource.Status.SUCCESS) {
                        String address = resource.source.getAddr();
                        addressText.setText(address);
                        loadAddressOntoView(address);
                    } else if (resource.state == Resource.Status.ERROR){
                        addressText.setText("Token 错误");
                        saveRqImageView.setVisibility(View.GONE);
                        copyAddressView.setVisibility(View.GONE);
                    }
                }
        );
    }

    private void loadAddressOntoView(String address) {
        try {
            // 创建地址二维码图片
            mAddressBitmap = EncodingHandler.createQRCode(address,
                    getResources().getDimensionPixelOffset(R.dimen.rq_code_image));

            addressImageView.setImageBitmap(mAddressBitmap);

            // 保存二维码
            saveRqImageView.setOnClickListener(v -> requestPermission());

            // 复制提币地址
            copyAddressView.setOnClickListener(v -> Androids.copyToChipBoard(
                    this, addressText.getText().toString()));
        } catch (Exception e) {
            Androids.makeText(e.getMessage());
        }
    }

    private void requestPermission() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_storage_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            ImageViews.saveImageToGallery(this, mAddressBitmap);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ImageViews.saveImageToGallery(this, mAddressBitmap);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_storage_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }
}
